package webx.actions;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.text.TextSearchQueryProvider;
import org.eclipse.search2.internal.ui.SearchMessages;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IStartup;

/**
 * 基于搜索项目和搜索关键字的WEB超链接搜索服务:
 * 解析网页超链接提交的字符串，获取参数"项目名称(scope)" 和 搜索"字符串(string)"
 * 并启动eclipse的文本搜索功能进行字符串搜索,用以替代CTRL+H然后手动输入.
 * html超链接代码:向插件内置服务 2014 socket端口提交要查找的项目和查找内容即是summery项目中的title noEmpty字符串：  
 *	<a href="http://localhost:2014/?scope=\\summery&string=title noEmpty">必输CSS样例</a>
 * @author 王华荣 2014.7.4
 *
 */
class FindRun extends Thread{
	// 搜索范围
	static String scope="";
	
	// 搜索字符串
	static String string = "";
	
	// 内置服务器端口2016
	int port = 2016;

	// 内置服务器
	private ServerSocket ser;
	
	public void run() {
		try {
			ser = new ServerSocket(port);
		}catch (IOException e) {
			try {
				if(ser!=null)
				ser.close();
			} catch (Exception e1) {e1.printStackTrace();}
		}
		
		while(true){
			InputStream ins = null;
			Socket explor = null;
			OutputStream os = null;
			try {
				if(ser == null) break;
				
				System.out.println("等待读取1111url get:");
				explor = ser.accept();
				ins = explor.getInputStream();
				//os = explor.getOutputStream();
				//os.write(0);
				int xx= ins.available()==0?1000:ins.available(); 
				byte[] httprequest_data = new byte[xx];
				ins.read(httprequest_data);
				String rstr = new String(httprequest_data,"UTF-8");
				System.out.println("读取url get:["+rstr+"]");
				String[] arr = rstr.split(" ");
				if(arr.length<=1){
					continue;
				}
				rstr = rstr.split(" ")[1];
				String param = rstr.substring(rstr.indexOf("?")+1);
				String[] params = param.split("&");
				for(int i=0;i<params.length;i++){
					String name = params[i].split("=")[0];
					String vale = params[i].split("=")[1];
                    vale = java.net.URLDecoder.decode(vale);
					if("scope".equals(name)){
						scope = vale;
					}
					if("string".equals(name)){
						string = vale;
					}
				}
				System.out.println("scope:"+scope);
				System.out.println("string:"+string);
			
				Display.getDefault().syncExec(new Runnable() {
			         public void run() {
			        	
			        	try{
			        	   // searching... 
			        	   // 文本查找调度
			        	   TextSearchQueryProvider provider = TextSearchQueryProvider.getPreferred();
			        	   System.out.println("provider:"+provider);
							try
							{   // 文本查找器
								ISearchQuery query = createQuery(provider,scope,string);
								
								if (query != null)
									// 搜索
									NewSearchUI.runQueryInBackground(query);
							}catch (OperationCanceledException _ex){
								_ex.printStackTrace();
							}
							catch (CoreException e){  
								e.printStackTrace();
								try{
									ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title,
										SearchMessages.RetrieverAction_error_message, e.getStatus());
								}catch(Exception ex){
									ex.printStackTrace();
								}
							}
						    // searching end
			        	}catch(Exception ex){
			        		ex.printStackTrace();
			        	}
			        	
			          }
			         }
			      );
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally{
				if(ins!=null){
					try {
						ins.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(os!=null){
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}	
			
		}
	}
	
	private Shell getShell(){
		return SearchPlugin.getActiveWorkbenchShell();
	}
	
	/**
	 * 
	 * @param provider
	 * @param scope 根据指定的资源搜索范围,进行搜索;多个路径以";"分割
	 * @param string 搜索字符串
	 * @return
	 * @throws CoreException
	 */
	protected ISearchQuery createQuery(TextSearchQueryProvider provider,String scope, String string) throws CoreException
	{
		//IWorkspace resource = ResourcesPlugin.getWorkspace();
		//IProject project = resource.getRoot().getProject(scope);
		ArrayList list = new ArrayList();
		String[] scopes = scope.split(";");
		for(int i=0;i<scopes.length;i++){
			IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(scopes[i]));
			if(iresource!=null && iresource.exists()){
				list.add(iresource);
			}
		}
		
		//if (project != null)
			return provider.createQuery(string,(IResource[])list.toArray(new IResource[0]));
		//else
		//	return provider.createQuery(string);
	}
}

public class Startup implements IStartup {
	public void earlyStartup() {
		Display.getDefault().syncExec(new Runnable() {
	         public void run() {
	        	 // start find server
	        	 // 启动搜索服务
	        	 new FindRun().start();
	         }
	      });
	   }
	
}